package com.qkbb.admin.kuibu.qkbb.fragment;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qkbb.admin.kuibu.R;
import com.qkbb.admin.kuibu.adapter.ViewPagerListAdapter;
import com.qkbb.admin.kuibu.qkbb.JavaBean.Game;
import com.qkbb.admin.kuibu.qkbb.activity.Route_details;
import com.qkbb.admin.kuibu.qkbb.funcation.HttpURLConnHelper;
import com.qkbb.admin.kuibu.qkbb.funcation.ImageDownloadSDCardCacheHelper;
import com.qkbb.admin.kuibu.qkbb.funcation.MD5Utils;
import com.qkbb.admin.kuibu.qkbb.funcation.MyImageCache;
import com.qkbb.admin.kuibu.qkbb.funcation.NetworkHelper;
import com.qkbb.admin.kuibu.qkbb.funcation.OSShelp;
import com.qkbb.admin.kuibu.qkbb.funcation.SDCardHelper;
import com.qkbb.admin.kuibu.qkbb.url.Url;
import com.qkbb.admin.kuibu.qkbb.view.CustomProgressDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;



/**
 * Created by admin on 2016/1/25.
 */

public class Recommend extends Fragment {
    private int Postion;
    private List<Game> listbody;
    private List<Game> listhead;
    private ViewPagerListAdapter adapter;
    private PullToRefreshListView listView;
    private android.os.Handler handler;
    private List<View> Viewlist;
    private static final int UPDATE = 0;
    private ImageView imageView;
    private TextView textView;
    private OSShelp osShelp;
    private int pager=1;
    private View HeadView;
    private URL url;
    private URL url1;
    private static List<String> listurl;
    private int roadid;
    private String roadname;
    private String user_token;
    private ListView lv;
    private ViewPager viewPager;
    private TextView textview;
    private View pagerview;
    private PagerAdapter pageradapter;
    private int i;
    private View newView;
    private CustomProgressDialog progressDialog;
    public Recommend(){

    }

    public int getPostion() {
        return Postion;
    }

    public void setPostion(int postion) {
        Postion = postion;
    }
        @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view=inflater.inflate(R.layout.fragment_route_viewpager, null);
            listView= (PullToRefreshListView) view.findViewById(R.id.fragment_route_viewpager_listview);
            listbody=new ArrayList<Game>();
            listhead=new ArrayList<Game>();
            listView.setMode(PullToRefreshBase.Mode.BOTH);
            listView.getLoadingLayoutProxy(false, true).setPullLabel("下拉刷新");
            listView.getLoadingLayoutProxy(false, true).setRefreshingLabel("刷新中");
            listView.getLoadingLayoutProxy(false, true).setReleaseLabel("上拉加载");
            user_token=SDCardHelper.loadFileFromSdCard("user_token", getActivity());
            pagerview = LayoutInflater.from(getActivity()).inflate(R.layout.headview_item, null);
            viewPager= (ViewPager) pagerview.findViewById(R.id.headview_item_viewpager);
            textview = (TextView) pagerview.findViewById(R.id.headview_item_textview);
            lv=listView.getRefreshableView();
            progressDialog= CustomProgressDialog.createDialog(getActivity());
            progressDialog.setTitle("加载中......");
            progressDialog.show();
            if (Postion==0&&newView==null){
                lv.addHeaderView(pagerview);
            }
            setListion();
            handler();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    getGames(pager,Postion+1);
                    Message message=new Message();
                    message.what=UPDATE;
                    handler.sendMessage(message);
                }
            }).start();
            return view;
    }

    private void handler() {
        handler=new android.os.Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (msg.what==UPDATE){
                    if (listbody.size()!=0){

                            adapter = new ViewPagerListAdapter(listbody, listhead, getActivity());
                            viewPager.setAdapter(pageradapter);
                            listView.setAdapter(adapter);
                            listView.onRefreshComplete();
                        progressDialog.cancel();

                    }
//                        if (Postion==0){
//                            if (HeadView==null){
//                                HeadView=getHeadView();
//                            }
//                            lv.addHeaderView(HeadView);
//                        }
                }
                if (msg.what==3){
                    adapter.notifyDataSetChanged();
                    listView.onRefreshComplete();
                }

                super.handleMessage(msg);
            }
        };
    }


    public void setListion(){

        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                Log.e("下拉","下拉");
                listhead.clear();
                listbody.clear();
                i++;
                pager=1;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getGames(pager,Postion+1);
                        Message message=new Message();
                        message.what=3;
                        handler.sendMessage(message);
                    }
                }).start();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pager++;
                Log.e("上拉","上拉");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getGames(pager,Postion+1);
                        Message message=new Message();
                        message.what=3;
                        handler.sendMessage(message);
                    }
                }).start();
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), Route_details.class);
                Log.e("postiontext", position + "");
                Log.e("idtext", "" + id);
               Game game= (Game) parent.getAdapter().getItem(position);

                    roadid=game.getRoadid();
                    roadname=game.getRoadname();
                Log.e("roadname",roadname);
                intent.putExtra("roadname",roadname);
                intent.putExtra("roadid",roadid);
                startActivity(intent);
//                if (position >= 1) {
//                    if (Postion == 0) {
//                        roadid = listbody.get(position - 2).getRoadid();
//                    } else {
//                        roadid = listhead.get(position - 1).getRoadid();
//                    }
//                    Log.e("roadid", roadid + "");
//                    Bundle bundle = new Bundle();
//                    bundle.putInt("roadid", roadid);
//                    intent.putExtra("bundle", bundle);
//                }
//                startActivity(intent);
            }
        });
    }
    public View getHeadView(){
        osShelp=new OSShelp(getActivity());
        getViewList();
            pageradapter=new PagerAdapter() {
                @Override
                public int getCount() {
                    Log.e("listhead", listhead.size() + "");
                    return listhead.size();
                }

                @Override
                public boolean isViewFromObject(View view, Object object) {
                    return view==object;
                }
                int postion;
                @Override
                public Object instantiateItem(ViewGroup container, int position) {
                    postion=position;
                    container.addView(Viewlist.get(position));
                    Viewlist.get(position).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Log.e("dddd", "ddd");
                            Intent intent = new Intent(getActivity(), Route_details.class);

                            roadid = listhead.get(postion).getRoadid();
                            roadname = listhead.get(postion).getRoadname();
                            Log.e("roadname", roadname);
                            intent.putExtra("roadname", roadname);
                            intent.putExtra("roadid", roadid);
                            startActivity(intent);
                        }
                    });
                    return Viewlist.get(position);
                }

                @Override
                public void destroyItem(ViewGroup container, int position, Object object) {
                    container.removeView(Viewlist.get(position));
                }
            };

        return pagerview;
    }

    private void getViewList() {
        if (Viewlist==null){
        Viewlist=new ArrayList<View>();
        }
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(final int position) {
                textview.setText(listhead.get(position).getRoadname());

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        for(int i=0;i<listhead.size();i++){
            ImageView headimageview=new ImageView(getActivity());
            headimageview.setScaleType(ImageView.ScaleType.FIT_XY);
            String uri=osShelp.getBitmap(listhead.get(i).getPictureurl());
//            imageLoader.get(uri, imageListener);
            new ImageDownloadSDCardCacheHelper().myDownloadImageSDCardCache(getActivity(),uri,headimageview,listhead.get(i).getPictureurl());
            Viewlist.add(headimageview);
        }
    }

    public void getGames(int page,int gamecategory){
        final String url= Url.GETGAMES1 + user_token + Url.GETGAMES2 + page + Url.GETGAMES3 + gamecategory;

                byte b[]=HttpURLConnHelper.loadByteFromURL(url,getActivity());
                if (b!=null) {
                    String str = new String(b);
                    Log.e("str", str);
                    bodyJson(str);
                }


    }

    private void bodyJson(String str) {
        try {
            JSONObject jsonObject = new JSONObject(str);
            JSONObject jsonObject1 = jsonObject.getJSONObject("data");
            JSONArray jsonArray = jsonObject1.getJSONArray("games");
            JSONArray jsonArray1 = jsonObject1.getJSONArray("banners");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                Game game = new Game();
                game.setRoadid(jsonObject2.getInt("roadid"));
                game.setRoadname(jsonObject2.getString("roadname"));
                Log.e("", jsonObject2.getString("roadname"));
                game.setDetailurl(jsonObject2.getString("detailurl"));
                game.setPictureurl(jsonObject2.getString("pictureurl"));
                game.setCategoryid(jsonObject2.getInt("categoryid"));
                game.setRoadsteplength(jsonObject2.getInt("roadsteplength"));
                game.setTotal_steps(jsonObject2.getInt("total_steps"));
                game.setNumber_of_participants(jsonObject2.getInt("number_of_participants"));
                game.setStarttime(jsonObject2.getString("starttime"));
                game.setDescription(jsonObject2.getString("description"));
                game.setEndtime(jsonObject2.getString("endtime"));
                listbody.add(game);
            }
            for (int i = 0; i < jsonArray1.length(); i++) {
                JSONObject jsonObject2 = jsonArray1.getJSONObject(i);
                Game game = new Game();
                game.setRoadid(jsonObject2.getInt("roadid"));
                game.setCategoryid(jsonObject2.getInt("categoryid"));
                game.setDetailurl(jsonObject2.getString("detailurl"));
                game.setRoadname(jsonObject2.getString("roadname"));
                game.setPictureurl(jsonObject2.getString("pictureurl"));
                game.setRoadsteplength(jsonObject2.getInt("roadsteplength"));
                game.setTotal_steps(jsonObject2.getInt("total_steps"));
                game.setNumber_of_participants(jsonObject2.getInt("number_of_participants"));
                game.setStarttime(jsonObject2.getString("starttime"));
                game.setEndtime(jsonObject2.getString("endtime"));
                Log.e("roadname", jsonObject2.getString("roadname"));
                listhead.add(game);
            }
                getHeadView();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e("listbody.size", listbody.size() + "");

    }

}
